package com.nf.health.app.activity.global;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.nf.health.app.MyApplication;
import com.nf.health.app.R;
import com.nf.health.app.core.HttpActionHandle;
import com.nf.health.app.http.HttpRequestProvider;
import com.nf.health.app.http.RequestProvider;
import com.nf.health.app.http.VolleyErrorHelper;
import com.nf.health.app.login.activity.LoginActivity;
import com.nf.health.app.mine.activity.SettingActivity;
import com.nf.health.app.models.BaseBean;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.AppManager;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.umeng.analytics.MobclickAgent;

import cn.jpush.android.api.JPushInterface;

/**
 * Activity Base
 *
 * @author LGS
 */
public abstract class BaseActivity extends FragmentActivity implements HttpActionHandle, OnClickListener {
    private int mLoadingCount = 0; // 计数器当前耗时操作的数量
    private LayoutInflater mInflater;
    private FrameLayout titleBar;
    private FrameLayout content;
    private ViewGroup mLoading;
    private Button l_error_data_btn;
    private ViewGroup dataError;
    protected RequestProvider provider;
    private ImageView iv_show_nodata_img;
    private TextView tv_show_nodata_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_base);
        getWindow().setBackgroundDrawable(null);
        mInflater = (LayoutInflater) (getParent() != null ? this.getParent() : this).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        titleBar = (FrameLayout) findViewById(R.id.activity_base_titlebar);
        content = (FrameLayout) findViewById(R.id.activity_base_content);
        mLoading = (ViewGroup) findViewById(R.id.l_my_activity_base_loading);
        dataError = (ViewGroup) findViewById(R.id.l_my_activity_base_data_error);
        l_error_data_btn = (Button) findViewById(R.id.l_error_data_btn);
        iv_show_nodata_img = (ImageView) findViewById(R.id.iv_show_nodata_img);
        tv_show_nodata_content = (TextView) findViewById(R.id.tv_show_nodata_content);
        provider = new RequestProvider(this);

        //设置透明状态栏
        ViewGroup contentFrameLayout = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        View parentView = contentFrameLayout.getChildAt(0);
        if (parentView != null && Build.VERSION.SDK_INT >= 14) {
            parentView.setFitsSystemWindows(true);
        }
        regisitlistener();
    }
   public void  regisitlistener(){
       l_error_data_btn.setOnClickListener(this);
   }
    /**
     *  加载错误数据
     */
    protected void showDataError() {
        dataError.setVisibility(View.VISIBLE);
    }
    /**
     * 显示错误提示图片和文字
     * @param
     * @param
     */
    protected void showDataErrorDefault() {
        showDataError(R.drawable.no_inquiry,"暂无数据");
    }
    /**
     * 显示错误提示图片和文字
     * @param
     * @param
     */
    protected void showDataError(int resId, String show_nodata_content) {
        iv_show_nodata_img.setImageResource(resId);
        tv_show_nodata_content.setText(show_nodata_content);
        dataError.setVisibility(View.VISIBLE);
    }
    /**
     * 无数据时显示文字
     * @param
     * @param
     */
    protected void showDataError(int resId) {
        iv_show_nodata_img.setImageResource(resId);
        dataError.setVisibility(View.VISIBLE);
    }
    /**
     * 无数据时显示和文字
     * @param
     * @param
     */
    protected void showDataError(String show_nodata_content) {
        tv_show_nodata_content.setText(show_nodata_content);
        dataError.setVisibility(View.VISIBLE);
    }

    protected void hideDataError() {
        dataError.setVisibility(View.GONE);
    }

    /**
     * 设置内容布局
     *
     * @param layoutResID
     */
    protected void setContent(int layoutResID) {
        content.removeAllViews();
        LayoutInflater.from(this).inflate(layoutResID, content);
    }

    /**
     * 设置标题栏布局
     *
     * @param layoutResID
     */
    public void setTitleBar(int layoutResID) {
        titleBar.removeAllViews();
        View v = getLayoutInflater(layoutResID);
        setTitleBar(v);
    }

    /**
     * 生成view
     *
     * @param nRes
     * @return
     */
    protected final View getLayoutInflater(final int nRes) {
        return mInflater.inflate(nRes, null);
    }

    /**
     * 设置标题栏
     *
     * @param v
     */
    public void setTitleBar(View v) {
        if (v != null) {
            showTitleBar();
            titleBar.removeAllViews();
            titleBar.addView(v, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

            View view = v.findViewById(R.id.titlebar_back_view);
            if (view != null) {
                view.setOnClickListener(this);
            }

        } else {
            hideTitleBar();
        }
    }

    /**
     * 显示标题栏
     */
    protected void showTitleBar() {
        titleBar.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏标题栏
     */
    protected void hideTitleBar() {
        titleBar.setVisibility(View.GONE);
    }

    /**
     * 获取activity标题栏
     *
     * @return
     */
    public ViewGroup getTitleBar() {
        return titleBar;
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        //注销掉

        if (TextUtils.isEmpty(response)) {
            //处理error
            showToast(VolleyErrorHelper.getMessage(error));
        } else {
            //处理response
            String code = JsonUtils.getKey2Value(response, "code");
            if ("2002".equals(code)) {
                if (Util.isLogin()) {
                    showToast("登录失效，请重新登录");
                }
                PreferenceHelper.putBoolean(PreferenceHelper.ISLOGIN, false);
                //未登录
                ActivityUtils.skipActivity(this, LoginActivity.class);
                EMClient.getInstance().logout(true);//退出环信登陆
            } else {
                try {
                    BaseBean bean = new Gson().fromJson(response, BaseBean.class);
                    if (TextUtils.isEmpty(bean.getMsg())) {
                        showToast("数据为空");
                    } else {
                        showToast(bean.getMsg());
                    }
                } catch (Exception e) {
                    showToast(response);
                }
            }
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        try {
            //处理response
            String code = JsonUtils.getKey2Value(object.toString(), "code");
            if ("9999".equals(code)) {
                ActivityUtils.showActivity(BaseActivity.this, SettingActivity.class);//个人设置
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void handleActionStart(String actionName, Object object) {
        showLoading();
    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
        hideLoading();
    }

    @Override
    protected void onResume() {
        //友盟统计
        MobclickAgent.onResume(this);
        JPushInterface.onResume(this);
        super.onResume();
    }

    @Override
    protected void onPause() {
        //友盟统计
        MobclickAgent.onPause(this);
        JPushInterface.onPause(this);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        MyApplication.getRefWatcher(this).watch(this);
        AppManager.getAppManager().finishActivity(this);
        cancelAllRequest();
        super.onDestroy();
    }

    /**
     * 显示正载加载
     */
    protected final void showLoading() {
        mLoadingCount++;
        mLoading.setVisibility(View.VISIBLE);
    }

    /**
     * 显示正载加载
     */
    protected final void showLoading(String msg) {
        mLoadingCount++;
        TextView tv_msg = (TextView) mLoading.findViewById(R.id.tv_message);
        tv_msg.setText(msg);
        tv_msg.setVisibility(View.VISIBLE);
        mLoading.setVisibility(View.VISIBLE);
    }

    /**
     * 不显示加载项
     */
    protected final void hideLoading() {
        this.hideLoading(false);
    }

    /**
     * 不显示加载项
     *
     * @param bForceHide 是否强制隐藏
     */
    protected final void hideLoading(boolean bForceHide) {
        mLoadingCount--;
        if (bForceHide) {
            mLoadingCount = 0;
        }
        if (mLoadingCount <= 0) {
            mLoading.setVisibility(View.GONE);
        }
    }

    /**
     * 取消所有请求
     */
    public void cancelAllRequest() {
        try {
            HttpRequestProvider client = new HttpRequestProvider(this, "");
            client.cancelAllRequest();
        } catch (Exception e) {


        }

    }

    /**
     * 显示提示
     *
     * @param resId
     */
    public void showToast(int resId) {
        showToast(getString(resId));
    }

    /**
     * 显示提示
     *
     * @param content
     */
    public void showToast(String content) {
        // 避免部分手机弹出小黑点问题
        if (TextUtils.isEmpty(content)) {
            return;
        }
        //Toast.makeText(BaseActivity.this, content, Toast.LENGTH_SHORT).show();
        GetToast.useString(BaseActivity.this, content);
    }

    @Override
    public Resources getResources() {
        //处理App字体大小不随系统设置而改变
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titlebar_back_view:
                finish();
                break;
            case R.id.l_error_data_btn:
                hideDataError();
                onRefresh();
                break;
            case R.id.l_error_netsetting_btn:
                break;
            default:
                break;
        }
    }

    protected void onRefresh() {

    }
}